package logic

import (
	"context"
	"errors"
	"houseRpc/models"

	"houseRpc/house"
	"houseRpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListHouseLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListHouseLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListHouseLogic {
	return &ListHouseLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListHouseLogic) ListHouse(in *house.ListHouseRequest) (*house.ListHouseResponse, error) {
	// todo: add your logic here and delete this line

	var err error
	var h models.House
	var houses []models.House
	var houseList []*house.HouseList
	query := models.DB.Model(&models.House{})

	if in.Keyword != "" {
		query = query.Where("title LIKE ? OR ads LIKE ?", "%"+in.Keyword+"%", "%"+in.Keyword+"%")
	}

	if in.MinPrice > 0 {
		query = query.Where("price >= ?", in.MinPrice)
	}

	if in.MaxPrice > 0 {
		query = query.Where("price <= ?", in.MaxPrice)
	}

	query = query.Order("price desc").Find(&houses)

	if err = h.GetHouseById(); err != nil {
		return nil, errors.New("房源信息获取失败")
	}
	//if h.Status != 1 {
	//	return nil, errors.New("房源信息获取失败")
	//}

	for _, hs := range houses {
		if h.Status != 2 {
			list := house.HouseList{
				Title:  hs.Title,
				Ads:    hs.Ads,
				Price:  hs.Price,
				UserId: hs.UserId,
			}
			houseList = append(houseList, &list)
		}
	}

	return &house.ListHouseResponse{
		List: houseList,
	}, nil
}
